#include <QGradient>
#include <QPainter>
#include <QTimer>
#include <math.h>
#include "waiting-widget.h"

WaitingWidget::WaitingWidget(QWidget *parent) :
    QLabel(parent), m_timer(new QTimer(this)), m_rotation(0), m_speed(5)
{
    m_timer->setSingleShot(false);
    connect (m_timer, &QTimer::timeout, this, static_cast<void(WaitingWidget::*)()>(&WaitingWidget::repaint));
    setStartAngle(0, false);
    setEndAngle(240, false);
    setStartColor(QColor(0, 0, 0, 255), false);
    setEndColor(QColor(0, 0, 0, 0), false);
    updateGradient();
}

bool WaitingWidget::isRunning() const
{
    return m_timer->isActive();
}

void WaitingWidget::setStartAngle (double startAngle, bool updateNow)
{
    m_startAngle = startAngle;
    m_gradientStartPoint = m_startAngle/360.0;
    m_arcStartAngle = m_startAngle * 16;
    if (updateNow)
        updateGradient();
}

void WaitingWidget::setEndAngle (double endAngle, bool updateNow)
{
    m_endAngle = endAngle;
    m_gradientEndPoint = m_endAngle/360.0;
    m_arcEndAngle = m_endAngle * 16;
    if (updateNow)
        updateGradient();
}

void WaitingWidget::setStartColor (QColor color, bool updateNow)
{
    m_gradientStartColor = color;
    if (updateNow)
        updateGradient();
}

void WaitingWidget::setEndColor (QColor color, bool updateNow)
{
    m_gradientEndColor = color;
    if (updateNow)
        updateGradient();
}

void WaitingWidget::setSpeed (double speed)
{
    m_speed = speed;
}


void WaitingWidget::startAnimation()
{
    m_timer->start(16); // 60 FPS
}

void WaitingWidget::stopAnimation()
{
    m_timer->stop();
}

void WaitingWidget::setPixmap(const QPixmap &pixmap)
{
    m_timer->stop();
    QLabel::setPixmap(pixmap);
}

void WaitingWidget::setText(const QString &text)
{
    m_timer->stop();
    QLabel::setText(text);
}

void WaitingWidget::clear()
{
    m_timer->stop();
    QLabel::clear();
}

void WaitingWidget::updateGradient()
{
    QConicalGradient gradient(0, 0, m_startAngle-2*qAbs(m_speed));
    QGradientStops stops;
    stops.append(QGradientStop(m_gradientStartPoint, m_gradientStartColor));
    stops.append(QGradientStop(m_gradientEndPoint, m_gradientEndColor));
    gradient.setStops(stops);
    QBrush brush(gradient);
    m_pen.setBrush(brush);
}

void WaitingWidget::paintEvent(QPaintEvent *event)
{
    if (!m_timer->isActive())
    {
        QLabel::paintEvent(event);
        return;
    }

    int length = qMin(width(), height());
    length -= length/8; // margin
    int halfLength = length * 0.5;
    m_pen.setWidth(length/8);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.translate(rect().center());
    painter.rotate(m_rotation);
    painter.setPen(m_pen);

    painter.drawArc(-halfLength, -halfLength, length, length, m_arcStartAngle, m_arcEndAngle);
    m_rotation = fmod((m_rotation + m_speed), 360.0);
}
